package edu.wschina.module_c_hanoitower;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class RankActivity extends AppCompatActivity {

    private int currentPage = 1;
    private int totalPages = 1;

    private boolean isLoading = false;  // 用于防止重复加载
    CustomAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rank);

        List<JSONObject> items = MyApp.getInstance().getRankItems();
        if (items.isEmpty()) {
            TextView nodate = findViewById(R.id.nodata);
            nodate.setVisibility(View.VISIBLE);
            return;
        }


        adapter = new CustomAdapter(new ArrayList<>());
        RecyclerView recyclerView = findViewById(R.id.listview);
        recyclerView.setHasFixedSize(true);
        //必须
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

//        totalPages = (items.size() / MyApp.getInstance().itemPerPage) + 1;
        totalPages = (items.size() + MyApp.getInstance().itemPerPage - 1) / MyApp.getInstance().itemPerPage;


        loadPageData();

        ImageView back = findViewById(R.id.img_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(RankActivity.this, HomeActivity.class));
                finish();
            }
        });


        ImageView next = findViewById(R.id.next);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //判断当前页是否超过总页数
                if (currentPage >= totalPages)
                    return;
                currentPage++;
                loadPageData();
            }
        });

        ImageView prev = findViewById(R.id.prev);
        prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                currentPage--;
                loadPageData();
            }
        });
        ImageView nextNext = findViewById(R.id.nextnext);
        nextNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                currentPage=totalPages;
                loadPageData();
            }
        });

        ImageView prePre = findViewById(R.id.prepre);
        prePre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                currentPage=1;
                loadPageData();
            }
        });

    }

    private void loadPageData() {
        int itemPerPage = MyApp.getInstance().itemPerPage;
        List<JSONObject> items = MyApp.getInstance().getRankItems();
        //排序
        Collections.sort(items, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject item1, JSONObject item2) {
                try {
                    // 首先比较分数（降序）
                    int scoreComparison = Integer.compare(item1.getInt("moves"),item2.getInt("moves"));
                    if (scoreComparison != 0) {
                        return scoreComparison;
                    }
                    // 如果moves相同，则比较持续时间（升序）
                    return Integer.compare(item1.getInt("duration"), item2.getInt("duration"));
                } catch (JSONException e) {
                    return 0;
                }
            }
        });

        /*@description:
        计算排名
        @author aimin 2025-01-10 16:44:57*/
        int rank = 1;
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = items.get(i);
            try {
                // 如果不是第一个元素，并且当前元素与前一个元素的 score 和 duration 都相同，则排名相同
                if (i > 0) {
                    JSONObject previousItem = items.get(i - 1);

                    if (item.getInt("moves") == previousItem.getInt("moves") && item.getInt("duration") == previousItem.getInt("duration")) {
                        // 保持 rank 不变
                    } else {
                        // 如果不相同，更新 rank
                        rank = rank + 1;
                        //rank=i+1;
                    }
                }
                item.put("id", rank);
            } catch (Exception e) {

            }
        }

        List<JSONObject> currentItems = new ArrayList<>();
        for (int i = 0; i < itemPerPage; i++) {
            int num = (currentPage - 1) * itemPerPage + i;
            if (num >= items.size()) {
                break;
            }
            JSONObject item = items.get(num);
            currentItems.add(item);  // 生成假数据
        }

        updateNavigationIcons();
        TextView info = findViewById(R.id.inform_opt);
        info.setText(String.format("total:%d, current %d/%d", items.size(), currentPage, totalPages));

        adapter.clearItems();
        adapter.addItems(currentItems);  // 将新数据添加到适配器
    }


    private void updateNavigationIcons() {
        ImageView next = findViewById(R.id.next);
        ImageView prev = findViewById(R.id.prev);


        if (currentPage == 1) {
            prev.setImageResource(R.drawable.left_1a);  // 浅色图标，不可点击
            prev.setClickable(false);  // 设置为不可点击
            next.setImageResource(R.drawable.right_1);  // 深色图标，可以点击
            next.setClickable(true);  // 设置为可点击
        } else if (currentPage == totalPages) { // 判断是否是最后一页
            prev.setImageResource(R.drawable.left_1);  // 深色图标，可以点击
            prev.setClickable(true);  // 设置为可点击
            next.setImageResource(R.drawable.right_1a);  // 浅色图标，不可点击
            next.setClickable(false);  // 设置为不可点击
        } else {  // 中间的页面
            prev.setImageResource(R.drawable.left_1);  // 深色图标，可以点击
            prev.setClickable(true);  // 设置为可点击
            next.setImageResource(R.drawable.right_1);  // 深色图标，可以点击
            next.setClickable(true);  // 设置为可点击
        }
    }


}
